<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item label="部门" name="department">
      <a-select v-model:value="formState.department" placeholder="请选择部门">
        <a-select-option value="经营部门">经营部门</a-select-option>
        <a-select-option value="生产部门">生产部门</a-select-option>
        <a-select-option value="行政部门">行政部门</a-select-option>
        <a-select-option value="其他部门">其他部门</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="原因" name="reason">
      <a-textarea v-model:value="formState.reason" />
    </a-form-item>
    <a-form-item label="数量" name="qty">
      <a-input v-model:value="formState.qty" />
    </a-form-item>
    <div class="flex justify-end">
      <a-button type="danger" @click="generate">自动生成</a-button>
    </div>
  </a-form>
</template>
<script lang="ts">
import { generateDeviceDistributeForm } from "@/api/mock/cloud";
import { distributeDevice } from "@/controller/Cloud";
import { CloudDevice, CloudDeviceDistributeForm } from "model";
import {
  defineComponent,
  inject,
  PropType,
  reactive,
  ref,
  toRaw,
  UnwrapRef,
} from "vue";
export default defineComponent({
  name: "DispatchCloudDeviceForm",
  props: {
    device: {
      type: Object as PropType<CloudDevice>,
      required: true,
    },
  },
  setup(props) {
    const refresh: Function = inject("refresh") ?? new Function();
    const formRef = ref();
    const formState: UnwrapRef<CloudDeviceDistributeForm> = reactive({
      equipmentId: props.device.id,
      department: undefined,
      reason: "",
      qty: "",
    });
    const rules = {
      department: [
        {
          required: true,
          message: "请输入分发部门",
          trigger: "blur",
        },
      ],
      reason: [
        {
          required: true,
          message: "请输入分发原因",
          trigger: "blur",
        },
      ],
      qty: [
        {
          required: true,
          message: "请输入分发数量",
          trigger: "blur",
        },
      ],
    };
    const onSubmit = async (): Promise<boolean> => {
      return await formRef.value
        .validate()
        .then(async () => {
          await distributeDevice(toRaw(formState));
          Object.assign(formState, {
            department: "",
            reason: "",
            qty: "",
          });
          refresh();
          return true;
        })
        .catch(() => {
          return false;
        });
    };
    const generate = () => {
      Object.assign(formState, generateDeviceDistributeForm());
    };
    return {
      formRef,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      other: "",
      formState,
      rules,
      onSubmit,
      location,
      generate,
    };
  },
});
</script>
